from infos import constants
from infos.models import News, Category
from infos.modules.index import index_blu
from flask import render_template, current_app, session, jsonify, request
from infos.utils.response_code import RET

#新闻列表
@index_blu.route('/news_list')
def news_list():
    """
        1.获取参数
        2.校验参数
        3.返回响应
    :return:
    """
    #获取参数
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    filters = []
    #判断是否为最新,数据库中cid=1为最新
    if cid != 1:
        filters.append(News.category_id == cid)
    # *filters将列表拆包成元素
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    news_lists = paginate.items
    total_pages = paginate.pages
    current_page = paginate.page
    news_dict_list = []
    for news in news_lists:
        news_dict_list.append(news.to_basic_dict())
    date ={
        'total_page':total_pages,
        'current_page':current_page,
        'news_dict_li':news_dict_list
    }
    return jsonify(errno=RET.OK,errmsg='成功',data=date)
#展示用户信息
@index_blu.route('/')
def hello_world():
    """
        展示用户信息
        1、尝试从redis中获取用户信息，
        2、如果有user_id,查询mysql获取用户的基本信息
        3、调用模型类中的to_dict方法
        4、返回数据给模板
    :return:
    """
    user_id = session.get('user_id')
    data = None
    if user_id:
        try:
            from infos.models import User
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    #新闻点击排行榜
        try:
            news_list = News.query.order_by(News.clicks.desc()).limit(6)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='查询新闻异常')
    #判断查询结果是否存在
        if not news_list:
            return jsonify(errno=RET.NODATA,errmsg='新闻数据不存在')
    #遍历查询排行新闻结果
        news_dict_list = []
        for news in news_list:
             news_dict_list.append(news.to_basic_dict())
    # 遍历查询分类
        categorys = Category.query.all()
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
    #调用模型类中的方法,获取用户基本信息
        data = {
            'user':user.to_dict() if user else None,
            'news_dict_list':news_dict_list,
            'category_list':category_list
        }

    return render_template('news/index.html', data=data)
@index_blu.route('/favicon.ico')
def get_favicon():
    return current_app.send_static_file('news/favicon.ico')

